package org.tksj.bim.mq.service;

import com.gitee.starblues.bootstrap.realize.PluginCloseListener;
import com.gitee.starblues.core.PluginCloseType;
import com.gitee.starblues.core.PluginInfo;
import io.vertx.core.Vertx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Set;


@Service
public class MqPlugin implements PluginCloseListener {


    @Autowired
    private  MqVerticle verticle;
    private Vertx vertx;
    private String deployedId;

    @PostConstruct
    public void init() {
        vertx = Vertx.vertx();
        try {
            vertx.deployVerticle(verticle);
            Set<String> strings = vertx.deploymentIDs();
            deployedId=strings.iterator().next();
        } catch (Throwable e) {
            System.out.println("mqtt module start error");
        }
    }

    @Override
    public void close(GenericApplicationContext applicationContext, PluginInfo pluginInfo, PluginCloseType closeType) {
        try{
            String strMsg=String.format("plugin close,type:{},pluginId:{}", closeType, pluginInfo.getPluginId());
            System.out.println(strMsg);
            if(deployedId!=null){
                vertx.undeploy(deployedId);
            }
            if(verticle.client!=null){
                verticle.stop();
            }
        }
        catch (Throwable e){
            System.out.println("mqtt module start error");
        }
    }
}
